package cc.lucien.service;

import cc.lucien.dao.UserDao;
import cc.lucien.utils.DBHelper;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginService {

    UserDao userDao = new UserDao();

    public String login(String username, String password, String inCode, String checkCode) {
        //校验验证码
        if (!checkCode.equalsIgnoreCase(inCode))
            return "check code error!";
        //校验账户密码
        String username2 = "";
        String password2 = "";
        ResultSet resultSet = userDao.findByUsernameAndPassword(username, password);
        try {
            while (resultSet.next()){
                username2 = resultSet.getString("username");
                password2 = resultSet.getString("password");
            }
        } catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBHelper.close();
        }
        if (!username.equals(username2) || !password.equals(password2))
            return "Wrong account or password!";

        return "success&username=" + username;
    }

    public byte[] getImg(String username) {
        //获取头像文件名
        String fileName = null;
        FileInputStream in = null;
        ResultSet resultSet = userDao.findByUsername(username);
        try {
            while (resultSet.next()) {
                fileName = resultSet.getString("imgurl");
            }
            if (fileName == null)
                return null;
            in = new FileInputStream("F:\\photo\\"+fileName);
            byte[] img = new byte[in.available()];
            in.read(img);
            in.close();
            return img;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            DBHelper.close();
        }
        return null;
    }
}
